package com.mall.pay.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.mall.common.util.RespResult;
import com.mall.pay.model.PayLog;
import com.mall.pay.service.IPayLogService;
import com.mall.pay.service.IWxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

/**
 * @author Darren
 * @date 2022-09-13 14:53
 * Description：
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Api(tags = "REST - ")
@RestController
@RequestMapping("/wx")
public class WxPayController {
    private final IPayLogService payLogService;
    private final RocketMQTemplate rocketMQTemplate;
    private final IWxPayService wxPayService;

    @GetMapping("/result")
    @ApiOperation(value = "支付结果回调")
    public RespResult payLog() {
        PayLog payLog = new PayLog(IdWorker.get32UUID(), 1, "test", "001", new Date());
        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(payLog)).build();
        rocketMQTemplate.sendMessageInTransaction("rocket", "log", message, null);
        return RespResult.ok();
    }

    @GetMapping("/pay")
    @ApiOperation(value = "预下单")
    public RespResult pay(@RequestParam Map<String, String> map) throws Exception {
        if (map == null || map.size() == 0)
            return RespResult.error("支付系统繁忙，请稍后再试!");
        Map<String, String> resultMap = wxPayService.preOrder(map);
        resultMap.put("orderNumber", map.get("out_trade_no"));
        resultMap.put("money", map.get("total_fee"));
        return RespResult.ok(resultMap);
    }
}
